<template>
	<span style='display:inline-block;'>
		<el-cascader
		 style='width:100%;'
		:options = 'areaList'
		:placeholder = 'placeholder'
		:props = '{"value" : valueField, "label" : labelField, "children" : childrenField}'
		v-model = 'selectedValues'
		@change = 'change'
		></el-cascader>
	</span>
</template>

<script>
	import { Request } from '@/utils'
	let request = new Request()
	let areaList = []
	
	
	function f (data, target, parentId){
		for(let i = 0; i < data.length; i++) {
			if(data[i]['parent_id'] == parentId){
				let item = Object.assign({}, data[i])
				item.children = []
				target.push(item)
				f(data, item.children, item.id)
			}
		}
	}
	
	
	export default {
		props : {
			initValues  : {
				type : Object,
				default : []
			},
			
			url        : {
				type  : String,
				default : ''
			},
			
			parentIdField : {
				type : String,
				default : 'parent_id'
			},
			
			levelField : {
				type : String,
				default : 'level'
			},
			
			topLevelValue : {
				type : Number,
				default : 0
			},
			
			levelCount : {
				type  : Number,
				default : 3
			},
			
			valueField : {
				type : String,
				default : 'id'
			},
			labelField : {
				type : String,
				default : 'name'
			},
			childrenField : {
				type : String,
				default : 'children'
			},
			placeholder : {
				type : String,
				default : '请选择'
			}
		},
		
		data () {
			return {
				levelIndexes   : [],
				selectedValues : [],
				areaList : []
			}
		},
		
		methods: {
			
			change : function(values){
				this.$emit('select', values)
			},
			
			createAreaList : function(data, target, parentId){
				
				data.forEach((v, i) => {
					if(v[this.parentIdField] == parentId){
						let item = Object.assign({}, v)
						item.children = []
						target.push(item)
						this.createAreaList(data, item.children, item[this.valueField])
					}
				})
			},
			
			filterList : function(data){
				data.forEach((v, i) => {
					if('children' in v){
						if(v.children.length == 0){
							delete data[i].children
						}else{
							this.filterList(data[i].children)
						}
						
					}
				})
			}
			
	    },
		
		created () {

			let initValues = this.initValues
			this.selectedValues = initValues
			
			request.get(this.url, res => {
				if(!res.data){
					return
				}
				
				this.createAreaList(res.data, this.areaList, 0)
				this.filterList(this.areaList)
				//console.log(JSON.stringify(this.areaList))
				
			})
			
			
		}
	}
</script>